package com.example.gomoku;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import java.io.ByteArrayOutputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

public class PersonCenterActivity extends AppCompatActivity {

    private static final int PICK_IMAGE_REQUEST = 1;

    private ImageView ivAvatar;
    private TextView tvNickname, tvAccount;
    private Button btnModifyNickname, btnModifyPassword, btnModifyAvatar, btnBack;
    private DBHelper dbHelper;
    private SharedPreferences prefs;
    private SharedPreferences.Editor editor;
    private String uid, uname, upwd;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_person_center);

        Init();
        dbHelper = new DBHelper(this);
        prefs = getSharedPreferences("user", Context.MODE_PRIVATE);
        editor = prefs.edit();
        loadInfo();

        btnModifyNickname.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showModifyNicknameDialog();
            }
        });

        btnModifyPassword.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showModifyPasswordDialog();
            }
        });

        btnModifyAvatar.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                openGallery();
            }
        });

        btnBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(PersonCenterActivity.this, MainActivity.class);
                startActivity(intent);
                finish();
            }
        });

    }

    private void loadInfo() {
        uid = prefs.getString("uid", "");
        upwd = prefs.getString("upwd", "");
        uname = prefs.getString("uname", "");

        tvAccount.setText("账号：" + uid);
        tvNickname.setText("昵称：" + uname);

        byte[] avatar = dbHelper.getUserAvatar(uid);
        if (avatar != null) {
            Bitmap bitmap = BitmapFactory.decodeByteArray(avatar, 0, avatar.length);
            ivAvatar.setImageBitmap(bitmap);
        }
    }

    private void Init() {
        ivAvatar = findViewById( R.id.ivAvatar );//初始化头像
        tvNickname = findViewById(R.id.tvNickname);//初始化昵称
        tvAccount = findViewById(R.id.tvAccount);//初始化账号

        btnModifyNickname = findViewById(R.id.btnModifyNickname);
        btnModifyPassword = findViewById(R.id.btnModifyPassword);//初始化修改密码按钮
        btnModifyAvatar = findViewById(R.id.btnModifyAvatar);//初始化修改头像按钮
        btnBack = findViewById(R.id.btnBack);//初始化返回主页面按钮
    }
    private void showModifyNicknameDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("修改昵称");

        final EditText input = new EditText(this);
        LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.MATCH_PARENT,
                LinearLayout.LayoutParams.WRAP_CONTENT);
        input.setLayoutParams(layoutParams);
        builder.setView(input);

        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                String newNickname = input.getText().toString();
                editor.putString("uname", newNickname);
                editor.apply();
                tvNickname.setText("昵称：" + newNickname);
                Toast.makeText(PersonCenterActivity.this, "昵称修改成功", Toast.LENGTH_SHORT).show();
            }
        });

        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.cancel();
            }
        });

        builder.show();
    }

    private void showModifyPasswordDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("修改密码");

        final EditText input = new EditText(this);
        LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.MATCH_PARENT,
                LinearLayout.LayoutParams.WRAP_CONTENT);
        input.setLayoutParams(layoutParams);
        builder.setView(input);

        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                String newPassword = input.getText().toString();
                editor.putString("upwd", newPassword);
                editor.apply();
                dbHelper.updatePassword(uid, newPassword);
                Toast.makeText(PersonCenterActivity.this, "密码修改成功", Toast.LENGTH_SHORT).show();
            }
        });

        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.cancel();
            }
        });

        builder.show();
    }

    private void openGallery() {
        Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        startActivityForResult(intent, PICK_IMAGE_REQUEST);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null && data.getData() != null) {
            Uri imageUri = data.getData();
            try {
                Bitmap bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), imageUri);
                ivAvatar.setImageBitmap(bitmap);

                ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
                bitmap.compress(Bitmap.CompressFormat.PNG, 100, outputStream);
                byte[] avatar = outputStream.toByteArray();
                dbHelper.updateUserAvatar(uid, avatar);
                Toast.makeText(this, "头像上传成功", Toast.LENGTH_SHORT).show();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

}